#!/bin/bash

echo "=== Redis 测试开始 ==="

# 启动 Redis 服务
echo "启动 Redis 服务..."
docker-compose -f redis-compose.yml up -d

# 等待 Redis 启动
echo "等待 Redis 启动..."
sleep 10

# 检查容器状态
if ! docker ps | grep -q "test-redis"; then
    echo "❌ Redis 容器启动失败"
    exit 1
fi

echo "✅ Redis 容器启动成功"

# 测试 Redis 连接
echo "测试 Redis 连接..."
if docker exec test-redis redis-cli -a redis123 ping > /dev/null 2>&1; then
    echo "✅ Redis 连接成功"
else
    echo "❌ Redis 连接失败"
    docker-compose -f redis-compose.yml logs redis
    exit 1
fi

# 测试基本 SET/GET 操作
echo "测试 SET/GET 操作..."
docker exec test-redis redis-cli -a redis123 set test_key "test_value" > /dev/null 2>&1
RESULT=$(docker exec test-redis redis-cli -a redis123 get test_key 2>/dev/null)
if [ "$RESULT" = "test_value" ]; then
    echo "✅ SET/GET 操作成功"
else
    echo "❌ SET/GET 操作失败，期望 'test_value'，实际 '$RESULT'"
    exit 1
fi

# 测试 Hash 操作
echo "测试 Hash 操作..."
docker exec test-redis redis-cli -a redis123 hset user:1 name "John" age 30 > /dev/null 2>&1
NAME=$(docker exec test-redis redis-cli -a redis123 hget user:1 name 2>/dev/null)
AGE=$(docker exec test-redis redis-cli -a redis123 hget user:1 age 2>/dev/null)
if [ "$NAME" = "John" ] && [ "$AGE" = "30" ]; then
    echo "✅ Hash 操作成功"
else
    echo "❌ Hash 操作失败"
    exit 1
fi

# 测试 List 操作
echo "测试 List 操作..."
docker exec test-redis redis-cli -a redis123 lpush test_list "item1" "item2" "item3" > /dev/null 2>&1
LIST_LEN=$(docker exec test-redis redis-cli -a redis123 llen test_list 2>/dev/null)
if [ "$LIST_LEN" = "3" ]; then
    echo "✅ List 操作成功"
else
    echo "❌ List 操作失败，期望长度 3，实际 $LIST_LEN"
    exit 1
fi

# 测试过期时间
echo "测试过期时间..."
docker exec test-redis redis-cli -a redis123 set expire_key "expire_value" EX 3 > /dev/null 2>&1
BEFORE=$(docker exec test-redis redis-cli -a redis123 get expire_key 2>/dev/null)
sleep 4
AFTER=$(docker exec test-redis redis-cli -a redis123 get expire_key 2>/dev/null)
if [ "$BEFORE" = "expire_value" ] && [ "$AFTER" = "" ]; then
    echo "✅ 过期时间测试成功"
else
    echo "❌ 过期时间测试失败"
    exit 1
fi

# 测试持久化
echo "测试持久化..."
docker exec test-redis redis-cli -a redis123 set persist_key "persist_value" > /dev/null 2>&1
docker exec test-redis redis-cli -a redis123 bgsave > /dev/null 2>&1
sleep 2
echo "✅ 持久化测试完成"

# 性能测试
echo "执行性能测试..."
docker exec test-redis redis-cli -a redis123 --latency-history -i 1 ping > /dev/null 2>&1 &
PING_PID=$!
sleep 3
kill $PING_PID 2>/dev/null
echo "✅ 性能测试完成"

# 测试内存使用
echo "检查内存使用情况..."
MEMORY=$(docker exec test-redis redis-cli -a redis123 info memory | grep used_memory_human | cut -d: -f2 | tr -d '\r')
echo "当前内存使用: $MEMORY"

echo "=== Redis 测试完成 ==="

# 选择是否停止服务
read -p "是否停止 Redis 服务? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    docker-compose -f redis-compose.yml down
    echo "Redis 服务已停止"
fi